/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package erp.financeiro.dao;

import erp.financeiro.Saldo;
import erp.financeiro.TipoTransacao;
import erp.financeiro.Transacao;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;

/**
 *
 * @author Koji
 */
public class SaldoDAO {

    public static Saldo criarSaldo(Transacao transacao){
        Saldo saldo = new Saldo();
        saldo.setData(new Date());
        saldo.setTransacao(transacao);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("erpfinanceiroPU");
        EntityManager em = emf.createEntityManager();

        Query query = em.createQuery("SELECT x FROM " + Saldo.class.getSimpleName()+ " x ORDER BY x.data DESC");
        query.setMaxResults(1);
        Saldo saldoAntigo;
        try{
            saldoAntigo = (Saldo) query.getSingleResult();
        } catch (NoResultException  e){
            saldoAntigo = new Saldo();
            saldoAntigo.setSaldo(new Double(0));
        }


        Double valorAntigo = saldoAntigo.getSaldo();
        Double valorAtual;
        if(transacao.getTipo().equals(TipoTransacao.PAGAMENTO)){
            valorAtual = valorAntigo - transacao.getValor();
        } else {
            valorAtual = valorAntigo + transacao.getValor();
        }
        NumberFormat format = new DecimalFormat("N.NN");
        format.format(valorAtual);
        saldo.setSaldo(valorAtual);

        em.getTransaction().begin();
        em.persist(saldo);
        em.getTransaction().commit();

        return saldo;
    }
    public static List<Saldo> buscarSaldos(Date dataInicio, Date dataTermino){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("erpfinanceiroPU");
        EntityManager em = emf.createEntityManager();

        Query query = em.createQuery("SELECT x FROM " + Saldo.class.getSimpleName() + " x WHERE x.data >= :inicio AND x.data <= :termino");
        query.setParameter("inicio", dataInicio);
        query.setParameter("termino", dataTermino);

        return query.getResultList();
    }

}
